import Vue from 'vue';
import store from "@/store";
import { returnDayValue } from "./date-time";
import md5 from './md5.js';
import { logReferrer } from '@/api/log';

export function addrSlice(address) {
    if (address) {
        let before = address.slice(0, 5);
        let after = address.slice(-5, address.length);
        return before + '***' + after;
    }
}

export const debounce = (fn, delay = 2000) => {
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer);
            timer = null
        }
        timer = setTimeout(() => {
            fn.apply(this, arguments);
            timer = null;
        }, delay)
    }
}

export const throttle = (fn, delay = 1000) => {
    // eslint-disable-next-line no-undef
    let _arguments = arguments
    let canRun = true
    return function () {
        if (!canRun) return
        canRun = false
        setTimeout(() => {
            fn.call(this, _arguments)
            canRun = true
        }, delay);
    }
}

export const toSeoFriendsChannel = (channelToken) => {
    let channels = {
        "1688": "0",
        "TAOBAO": "1",
        "WEIDIAN": "2",
        "JD": "3"
    }
    return channels[channelToken] || channelToken;
}

export const fromSeoFriendsChannel = (channelId) => {
    let channels = {
        "0": "1688",
        "1": "TAOBAO",
        "2": "WEIDIAN",
        "3": "JD"
    }
    return channels[channelId] || channelId;
}

/*手机号隐藏中间4位数*/
export function phoneHide(val) {
    if (val) {
        return val.substr(0, 3) + '****' + val.substr(-4);
    } else {
        return '***********'
    }
}
/**
 * 生成随机uuid
 */
export const getFileNameUUID = () => {
    function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    return `${+new Date()}_${rx()}${rx()}`
}
/**
 * 跳转discord外链
 */
export const jumpDiscord = () => {
    // window.open('https://discord.com/invite/t7xmAYwZhU', '_blank');
    window.open('https://discord.com/invite/H5fEeBCY3y', '_blank');
}

/**
 * 复制分享链接
 */
export function copyInviteLink() {
    if (localStorage.getItem('USER_TOKEN')) {
        let link = `${store.state.config.config.webDomain}/register?inviteCode=${store.state.user.userInfo.inviteCode}`;
        return link;
    } else {
        this.$router.push('/login')
    }
}

export function showImagesByIndex(photosList, initialViewIndex) {
    // 判断photosList和initialViewIndex是否合法
    if (!Array.isArray(photosList) || typeof initialViewIndex !== 'number') {
        console.error('参数不合法，请检查传入的图片列表和初始查看索引');
        return;
    }

    Vue.prototype.$viewerApi({
        images: photosList,
        options: {
            initialViewIndex: initialViewIndex,
        },
    });
}

/**
 * 登录参数加密
 * @param str string 登录+密码
 * @return object signture - 签名    timestamp - 时间戳
 */
export const mdByLogin = (str) => {
    let time = returnDayValue();
    return {
        signture: md5.hex_md5(`${str}${String(time).slice(-5)}`),
        timestamp: time
    }
}


/**
 * 跳转到外部链接
 */
export const isJumpWeb = (url) => {
    if (url == null || url == '') {
        return;
    }
    window.open(url, '_blank');
}

/**
 * 根据用户昵称第一个字母，返回一个渐变色背景
 * @param str string 字符串
 */
const avatarBgList = [
    'linear-gradient( 180deg, #B6B5B9 0%, #9A9A9E 100%)',
    'linear-gradient( 180deg, #FF97AF 0%, #FF7596 100%)',
    'linear-gradient( 180deg, #FF8279 0%, #FF584C 100%)',
    'linear-gradient( 180deg, #FFB96E 0%, #FFA136 100%)',
    'linear-gradient( 180deg, #FFD772 0%, #FFCC40 100%)',
    'linear-gradient( 180deg, #91E59A 0%, #66DE77 100%)',
    'linear-gradient( 180deg, #95DAFC 0%, #71CEFA 100%)',
    'linear-gradient( 180deg, #BCA8FB 0%, #A58BF8 100%)',
    'linear-gradient( 180deg, #90ECFF 0%, #55D3EC 100%)',
    'linear-gradient( 180deg, #FFB6EA 0%, #F58DDA 100%)'
]
export function avatarBg(str = '0') {
    let index = str.charCodeAt(0) % 10;
    return { text: str.charAt(0), bg: avatarBgList[index] }
}


/**
 * 储存的key + 用户id 与所储存的值
 * @param key string 储存的key
 * @param obj string 储存的数据
 */
export const setUserIdVal = (key, obj) => {
    let k = store.state.user.userInfo.id;
    if (k) {
        localStorage.setItem(`${key}_${k}`, obj);
    }
}

/**
 * 获取本地储存的key + 用户id 与所储存的值
 * @param key string 储存的key
 * @return 储存的数据
 */
export const getUserIdVal = (key) => {
    let k = store.state.user.userInfo.id;
    if (k) {
        return localStorage.getItem(`${key}_${k}`);
    } else {
        return '';
    }
}

/**
 * 根据地址信息，判断重复数据
 * @param info object
 * @param codeExamine boolean 是否检查邮编
 * @param examineUrl string 查询的页面 
 * 	edit地址的编辑与新增(/pages/user/setting/address/set-address) 
 * 	parcel提交包裹(/pages/user/submit/parcel) 
 * 	order确认订单(/pages/pay/confirm-order)
 * 	diy自定义订单(/pages/diy-order/index)
 * 	transport转运订单(/pages/transport/index)
 */
export function addressExamineRepetition(info, codeExamine = false, examineUrl = 'edit') {
    //省
    let provinceText = info.provinceText ? info.provinceText.toLowerCase() : '';
    //市
    let cityText = info.cityText ? info.cityText.toLowerCase() : '';
    // 门牌号
    let doorNumber = info.doorNumber ? info.doorNumber.toLowerCase() : '';
    // 详细地址
    let addressDetail = info.addressDetail ? info.addressDetail.toLowerCase() : '';
    //邮编
    let postalCode = info.postalCode ? info.postalCode : '';
    // 建议邮编
    let recommendedPostalCode = info.recommendedPostalCode ? info.recommendedPostalCode : '';
    return new Promise((r, j) => {
        //在提交包裹、提交订单中，有储存改地址id，则不提示
        let keyStorage = `EXAMINE_${examineUrl}`;
        let storageExamine = getUserIdVal(keyStorage) ? JSON.parse(getUserIdVal(keyStorage)) : [];
        console.log(storageExamine, info.id);
        let id = info.addressId ? info.addressId : info.id;
        if (examineUrl != 'edit' && storageExamine && id && storageExamine.includes(id)) {//该用户本地有储存该地址，即已经有提示过，则不在提示
            r();
            return;
        }


        // 确保输入为字符串类型并去除首尾空格 构建正则表达式，\s* 表示匹配零个或多个空格，'i' 表示不区分大小写
        provinceText = typeof provinceText === 'string' ? provinceText.trim() : '';
        cityText = typeof cityText === 'string' ? cityText.trim() : '';
        addressDetail = typeof addressDetail === 'string' ? addressDetail.trim() : '';
        postalCode = typeof postalCode === 'string' ? postalCode.trim() : '';
        doorNumber = typeof doorNumber === 'string' ? doorNumber.trim() : '';

        const provinceRegex = new RegExp(provinceText.replace(/\s/g, '\\s*'), 'i');
        const cityRegex = new RegExp(cityText.replace(/\s/g, '\\s*'), 'i');
        const postalCodeRegex = new RegExp(postalCode.replace(/\s/g, '\\s*'), 'i');
        const doorNumberRegex = new RegExp(doorNumber.replace(/\s/g, '\\s*'), 'i');

        //详细地址里有省、市
        if ((provinceText && addressDetail && provinceRegex.test(addressDetail)) ||
            (cityText && addressDetail && cityRegex.test(addressDetail))) {
            j({ text: 'user.addressExamineLoaction' });
            storageExamine.push(info.addressId ? info.addressId : info.id);
            setUserIdVal(keyStorage, JSON.stringify(storageExamine));
            return;
        }

        //详细地址里有门牌号
        let doorArr = doorNumber.split(" ");
        let addressArr = new Set(addressDetail.split(" "));
        let sameValues = doorArr.filter(item => addressArr.has(item))
        if (doorNumber && addressDetail && (sameValues.length || (doorNumberRegex.test(addressDetail)))) {
            j({ text: 'user.addressExamineHouse' });
            storageExamine.push(info.addressId ? info.addressId : info.id);
            setUserIdVal(keyStorage, JSON.stringify(storageExamine));
            return;
        }

        //详细地址里有邮编
        if (codeExamine && addressDetail && postalCode && postalCodeRegex.test(addressDetail)) {
            j({ text: 'user.addressModuleCode' });
            storageExamine.push(info.addressId ? info.addressId : info.id);
            setUserIdVal(keyStorage, JSON.stringify(storageExamine));
            return;
        }

        //门牌号里有省、市
        if ((doorNumber && provinceText && provinceRegex.test(doorNumber)) || (doorNumber && cityText && cityRegex.test(doorNumber))) {
            j({ text: 'user.create_tip1' });
            storageExamine.push(info.addressId ? info.addressId : info.id);
            setUserIdVal(keyStorage, JSON.stringify(storageExamine));
            return;
        }

        //邮编校验建议
        if (postalCode && recommendedPostalCode && recommendedPostalCode != postalCode) {
            storageExamine.push(info.addressId ? info.addressId : info.id);
            setUserIdVal(keyStorage, JSON.stringify(storageExamine));
            j({ text: 'user.postal_code' });
            return;
        }
        r();
    })
}

/**
 * 校验地址必填信息
 * @param info object
 */
export function validateAddressRequired(info) {
    if (info.recipientName) {
        let name = info.recipientName || '';
        //名、姓
        if (name.indexOf(',') == -1) {
            return;
        }
    } else {
        //名、姓
        if (!info.name) {
            return;
        }
        if (!info.surname) {
            return;
        }
    }
    //国家
    if (!info.countryText) {
        return;
    }
    //省
    if (!info.provinceText) {
        return;
    }
    //城市
    // if (!info.cityText) {
    //   return;
    // }
    //详细地址
    if (!info.addressDetail) {
        return;
    }
    //邮编
    if (!info.postalCode) {
        return;
    }
    //区号
    if (!info.regionCode) {
        return;
    }
    //手机号
    if (!info.mobile) {
        return;
    }
    //手机号校验
    let reg = /^[0-9()\-]*$/;
    if (!reg.test(info.mobile)) {
        return;
    }
    return true;
}

/**
 * 图片压缩 - 不改变原来图片尺寸，降低质量
 * @param url string 图片地址 可base64
 */
export function imagesCompress(url) {
    return new Promise((r, j) => {
        let img = new Image();
        img.crossOrigin = "Anonymous"; // 处理跨域问题
        img.src = url;
        img.onload = () => {
            let canvas = document.createElement('canvas');
            let context = canvas.getContext('2d');
            let cw = img.width;
            let ch = img.height;
            let w = cw;
            let h = ch;
            // 限制最大宽高 600px
            // if (cw > 600 || ch > 600) {
            //   if (cw > ch) {
            //     w = 600;
            //     h = (600 * ch) / cw;
            //   } else {
            //     h = 600;
            //     w = (600 * cw) / ch;
            //   }
            // }
            canvas.width = w;
            canvas.height = h;
            context.clearRect(0, 0, w, h);
            context.drawImage(img, 0, 0, w, h);
            // 输出压缩后的 base64 图片（jpeg 格式，50% 质量）
            let base64 = canvas.toDataURL('image/jpeg', 0.5);
            r(base64);
        }
        img.onerror = err => {
            j(err);
        };
    })
}

/**
 * 根据用户昵称第一个字母，返回一个渐变色背景
 * @param str string 字符串
 */
const avatarRandomBgList = [
    'linear-gradient( 180deg, #B6B5B9 0%, #9A9A9E 100%)',
    'linear-gradient( 180deg, #FF97AF 0%, #FF7596 100%)',
    'linear-gradient( 180deg, #FF8279 0%, #FF584C 100%)',
    'linear-gradient( 180deg, #FFB96E 0%, #FFA136 100%)',
    'linear-gradient( 180deg, #FFD772 0%, #FFCC40 100%)',
    'linear-gradient( 180deg, #91E59A 0%, #66DE77 100%)',
    'linear-gradient( 180deg, #95DAFC 0%, #71CEFA 100%)',
    'linear-gradient( 180deg, #BCA8FB 0%, #A58BF8 100%)',
    'linear-gradient( 180deg, #90ECFF 0%, #55D3EC 100%)',
    'linear-gradient( 180deg, #FFB6EA 0%, #F58DDA 100%)'
];

export function avatarRandomBg(str = '0') {
    // 生成一个 0 到 avatarRandomBgList.length - 1 之间的随机整数
    const randomIndex = Math.floor(Math.random() * avatarRandomBgList.length);
    return { text: str.charAt(0), bg: avatarRandomBgList[randomIndex] };
}

//处理数字只能输入小数点后2位
/**
 * 处理数字只能输入小数点后2位
 * @param val number 
 * @return number
 */
export function inputDigit(val){
	val = val.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符  
	val = val.replace(/^\./g,""); //验证第一个字符是数字而不是  
	val = val.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的  
	val = val.replace(".","$#$").replace(/\./g,"").replace("$#$",".");  
	val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数  3位小数则\d\d\d
	return val;
}


// 打点 - 从其他地方进入xxx页面，记录并且打点
export function dottingFirstEntry (){
	let sourceUrl = document.referrer;//来源地址
	let sourceUrlStorage = sessionStorage.getItem('sourceUrl');//本地记录的来源地址
	let isLogin = localStorage.getItem('USER_TOKEN') ? 1 : 0;//是否登录 0未登录 1登录
	let hrefUrl = window.location.href;//当前页面地址
	if(!sourceUrlStorage){
		try{
			let data = {
				uid:isLogin,
				ref:sourceUrl,
				u:hrefUrl
			}
			logReferrer(data);
			//储存来源地址，并且打点
			sessionStorage.setItem('sourceUrl',sourceUrl?sourceUrl:hrefUrl);
		}catch(e){
			//TODO handle the exception
		}
	}
}